package com.water.dynamic;

import com.water.service.IService;
import com.water.service.TeamService;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @author wsj
 * @version 1.0
 * @description: TODO
 * @date 2022/1/9 13:48
 */
public class MyJDKProxy {
    public static void main(String[] args) {
        final TeamService teamService = new TeamService();//被代理对象
        IService service  = (IService)  Proxy.newProxyInstance(
                teamService.getClass().getClassLoader(),
                teamService.getClass().getInterfaces(),
                new InvocationHandler(){
                    @Override
                    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                        try{
                            System.out.println("=======开始事务=========");
                            Object invoke = method.invoke(teamService,args);
                            System.out.println("======提交事务==========");
                            return invoke;
                        }catch (Exception e){
                            System.out.println("======回滚事务========");
                            e.printStackTrace();
                            throw e;
                        }finally {
                            System.out.println("=======finally===");

                        }
                    }
                }
        );
        service.add();
        System.out.println(teamService.getClass());
        System.out.println(service.getClass());
        System.out.println("-------结束------------");
    }
}
